package cn.wizzer.app.web.modules.controllers.crown;

import cn.wizzer.app.crown.modules.models.CrownMatch;
import cn.wizzer.app.crown.modules.models.constant.CrownRedisConstant;
import cn.wizzer.app.crown.modules.models.enums.MatchStageEnum;
import cn.wizzer.app.crown.modules.models.enums.PlayWayEnum;
import cn.wizzer.app.crown.modules.services.CrownMatchService;
import cn.wizzer.app.match.modules.models.constant.Fields;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.exceptions.BizException;
import cn.wizzer.framework.filter.ParamFilter;
import cn.wizzer.framework.page.Pagination;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.ApiParam;
import org.nutz.dao.pager.Pager;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;
import redis.clients.jedis.ScanParams;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 皇冠赛事Controller
 *
 * @author
 */
@At("/api/match/hg")
@IocBean
@Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
public class ApiCrownMatchController {

    @Inject
    private RedisService redisService;

    @Reference
    @Inject
    private CrownMatchService crownMatchService;

    @Reference
    @Inject
    private SysParamService sysParamService;


    /**
     * 查询联赛列表
     *
     * @return
     */
    @At("/leagueList")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result leagueList(
            @Param("stage") @ApiParam(required = true, example = "'FUTURE','BROWSE','RUNNING'") MatchStageEnum stage,
            @Param("sportType") @ApiParam(required = true, example = "'FOOTBALL','BASKETBALL'") String sportType) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        String key = Fields.PREFIX_CROWN + sportType + Fields.PREFIX_CROWN + stage + Fields.SUFFIX_LEAGUE;
        return Result.success().addData(redisService.lrange(key, 0, -1));
    }

    /**
     * 查询单式玩法相关的赛事列表
     *
     * @return Result
     */
    @At("/matchList")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result matchList(@Param("stage") @ApiParam(required = true, example = "'FUTURE','BROWSE','RUNNING'") MatchStageEnum stage,
                            @Param("sportType") @ApiParam(required = true, example = "'FOOTBALL','BASKETBALL'") String sportType,
                            @Param("keyWord") String keyWord,
                            @Param("pageNo") @ApiParam(required = true) int pageNo,
                            @Param("pageSize") @ApiParam(required = true) int pageSize
    ) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        Pagination pagination = crownMatchService.matchList(stage, sportType, keyWord, pageNo, pageSize);
        return Result.success().addData(pagination);
    }

    /**
     * 根据比赛ID 查询所有玩法
     *
     * @param id 比赛ID
     * @return Result
     */
    @At("/allPlayWay")
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result allPlayWay(@Param("id") @ApiParam(required = true) String id,
                             @Param("playWay") @ApiParam(required = true) PlayWayEnum playWay) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        String playWayKey;
        if (PlayWayEnum.P3.equals(playWay)) {
            playWayKey = CrownRedisConstant.P3;
        } else if (PlayWayEnum.R.equals(playWay)) {
            // 拼接单式玩法RedisKey
            playWayKey = CrownRedisConstant.SIMPLEX;
        } else {
            throw new BizException("停止注单");
        }
        // 拼接redis中的match key
        String matchKey = Fields.PREFIX_CROWN + "*" + Fields.KEY_JOIN + playWay + Fields.KEY_JOIN + "*"
                + Fields.SUFFIX_MATCH + Fields.KEY_COLON + id;
        // 从redis中获取match
        ScanParams scanParams = new ScanParams();
        scanParams.count(Integer.MAX_VALUE);
        scanParams.match(matchKey);
        List<String> matchList = redisService.scan("0", scanParams).getResult();
        if (CollectionUtils.isNotEmpty(matchList)) {
            CrownMatch match = JSONUtil.parseStringToJavaBean(CrownMatch.class, redisService.get(matchList.get(0)));
            return Result.success().addData(crownMatchService.composeMatch(playWayKey, match));
        }else {
            return Result.error("赛事已关闭");
        }
    }


    /**
     * 查询P3玩法相关的赛事列表
     *
     * @return Result
     */
    @At("/p3MatchList")
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result p3MatchList(@Param("sportType") @ApiParam(required = true, example = "'FOOTBALL','BASKETBALL'") String sportType,
                              @Param("keyWord") String keyWord,
                              @Param("pageNo") @ApiParam(required = true) int pageNo,
                              @Param("pageSize") @ApiParam(required = true) int pageSize) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        return Result.success(crownMatchService.p3MatchList(sportType, keyWord, pageNo, pageSize));
    }

    /**
     * 赛果列表
     *
     * @param start
     * @param end
     * @param pager
     * @param sportType
     * @return
     */
    @At("/resultList")
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result resultList(@ApiParam(required = false) Long start,
                             @ApiParam(required = false) Long end,
                             @Param("playWay")@ApiParam(required = true) PlayWayEnum playWay,
                             Pager pager,
                             @Param("sportType") String sportType) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }

        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(start * 1000));
        String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(end * 1000));

        Pagination pagination = crownMatchService.results(startTime, endTime, playWay, pager, sportType);
        return Result.success(pagination);
    }

    /**
     * 赛果详情
     *
     * @param id
     * @return
     */
    @At("/resultDetail")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result resultDetail(@ApiParam(required = true) String id) {
        return Result.success(crownMatchService.subResult(id, null));
    }

    /**
     * 查询冠军玩法相关的赛事列表
     *
     * @param sportType
     * @param pageNo
     * @param pageSize
     * @return
     */
    @At("/championMatchList")
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result championMatchList(@Param("sportType") @ApiParam(required = true, example = "'FOOTBALL','BASKETBALL'") String sportType,
                                    @Param("keyWord") String keyWord,
                                    @Param("pageNo") @ApiParam(required = true) int pageNo,
                                    @Param("pageSize") @ApiParam(required = true) int pageSize) {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        return Result.success(crownMatchService.championList(sportType, keyWord, pageNo, pageSize));
    }


    /**
     * 比赛统计
     *
     * @return
     */
    @At("/matchCount")
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result matchCount() {
        if (!sysParamService.fetch().getGameSwitch()) {
            // 前端大佬要code=0，data为false。
            return Result.success(false);
        }
        String crownMaintain = redisService.get(CrownRedisConstant.CROWN_MAINTAIN);
        // 如果维护
        if (Strings.isNotBlank(crownMaintain)) {
            return Result.success();
        } else {
            return Result.success(crownMatchService.matchCount());
        }
    }

}





